package com.five.taotao.search;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.five.taotao.Adapter.GridAdapter;
import com.five.taotao.Adapter.GridResultAdapter;
import com.five.taotao.Application.MyApplication;
import com.five.taotao.R;
import com.five.taotao.dao.ProductListBeanDao;
import com.five.taotao.entity.Product;
import com.five.taotao.product_details.ProductDetailsActivity;
import com.five.taotao.util.Constants;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;


/**
 * A simple {@link Fragment} subclass.
 */
public class SearchResultFragment extends Fragment {

    @BindView(R.id.gridview1)
    PullToRefreshGridView gridview;

    private View v;
    private GridResultAdapter adapter;
    private List<Product.ListBean> mData;

    private ProductListBeanDao dao;
    private int page = 1;
    private int id = 1;

    public SearchResultFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (v == null) {
            v = inflater.inflate(R.layout.fragment_search_result, container, false);
            ButterKnife.bind(this, v);
            dao = new ProductListBeanDao(getActivity());

            final int productType = getArguments().getInt("productType");
            final String search_name = getArguments().getString("search_name");
            id = getArguments().getInt("id");

            mData = new ArrayList<>();
            adapter = new GridResultAdapter(mData, getActivity());
            gridview.setAdapter(adapter);

            if (search_name == null || search_name.equals("")) {
                loadData(productType + "");
            } else {
                refresh(search_name);
            }

            gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(getActivity(), ProductDetailsActivity.class);
                    intent.putExtra("product", mData.get(position));
                    startActivity(intent);
                }
            });


            gridview.setMode(PullToRefreshBase.Mode.BOTH);//下拉模式 两种
            gridview.setScrollingWhileRefreshingEnabled(true);//刷新模式仍可以滑动
            gridview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
                @Override
                public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                    if (search_name == null || search_name.equals("")) {
                        loadData(productType + "");
                    }
                }

                @Override
                public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                    if (search_name == null || search_name.equals("")) {
                        loadMore(productType + "");
                    }
                }
            });
        }

        return v;
    }

    /**
     * 刷新搜索结果
     */
    public void refresh(String name) {
        String tmp = null;
        try {
            tmp = URLEncoder.encode(name, "utf-8");
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }
        OkHttpUtils
                .post()
                .url(Constants.S_URL)
                .addParams("name", tmp)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        MyApplication.toast.toastShow("网络异常，请检查网络.");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        Product musicWebAlbum = gson.fromJson(response, Product.class);
                        List<Product.ListBean> items = musicWebAlbum.getList();
                        mData.clear();
                        mData.addAll(items);
                        adapter.notifyDataSetChanged();
                    }
                });

    }


    public void loadMore(String productType) {

        page++;

        String tmpURL = null;
        if (id == 1) {
            tmpURL = Constants.C_URL;
        } else if (id == 2) {
            tmpURL = Constants.SE_URL;
        } else if (id == 3) {
            tmpURL = Constants.C_URL;
        } else if (id == 4) {
            tmpURL = Constants.SP_URL;
        }

        OkHttpUtils
                .post()
                .url(tmpURL)
                .addParams("id", productType)
                .addParams("page", page + "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        Product musicWebAlbum = gson.fromJson(response, Product.class);
                        List<Product.ListBean> items = musicWebAlbum.getList();
                        mData.addAll(items);
                        adapter.notifyDataSetChanged();
                        gridview.onRefreshComplete();
                    }
                });


    }


    public void loadData(String productType) {
        page = 1;
        if (productType.equals("0")) {
            mData.clear();
            mData.addAll(dao.findAllProduct());
            adapter.notifyDataSetChanged();
        } else {
            String tmpURL = null;
            if (id == 1) {
                tmpURL = Constants.C_URL;
            } else if (id == 2) {
                tmpURL = Constants.SE_URL;
            } else if (id == 3) {
                tmpURL = Constants.C_URL;
            } else if (id == 4) {
                tmpURL = Constants.SP_URL;
            }

            OkHttpUtils
                    .post()
                    .url(tmpURL)
                    .addParams("id", productType)
                    .addParams("page", page + "")
                    .build()
                    .execute(new MyCallBack());
        }


    }

    /**
     * 网络监听回调方法
     */
    private class MyCallBack extends StringCallback {

        @Override
        public void onResponse(String response, int id) {
            Gson gson = new Gson();
            Product musicWebAlbum = gson.fromJson(response, Product.class);
            List<Product.ListBean> items = musicWebAlbum.getList();
            mData.clear();
            mData.addAll(items);
            adapter.notifyDataSetChanged();
            gridview.onRefreshComplete();
        }

        @Override
        public void onError(Call call, Exception e, int id) {

        }
    }


}
